////////////////////////////	菜单背景场景初始化///////////////////////////////////
var radius = 100, theta = 0;
var angle = 0.01;
function backgroundScene(){
    Menu_width = document.getElementById('canvas-background').clientWidth;
    Menu_height = document.getElementById('canvas-background').clientHeight;
    Menu_renderer = new THREE.WebGLRenderer({
        antialias : true
    });
    Menu_renderer.setSize( window.innerWidth, window.innerHeight);
    document.getElementById('canvas-background').appendChild(Menu_renderer.domElement);
    Menu_renderer.setClearColor(0xFFFFFF, 1.0);
    Menu_camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 10000 );

    Menu_scene = new THREE.Scene();

    var Menu_light = new THREE.DirectionalLight( 0xffffff, 1 );
    Menu_light.position.set( 1, 1, 1 ).normalize();
    Menu_scene.add( Menu_light );

    var Menu_light = new THREE.DirectionalLight( 0xffffff, 1 );
    Menu_light.position.set( -1, -1, -1 ).normalize();
    Menu_scene.add( Menu_light );

    var geometry = new THREE.BoxGeometry( 20, 20, 20 );

    for ( var i = 0; i < 2000; i ++ ) {

        var object = new THREE.Mesh( geometry, new THREE.MeshLambertMaterial( { color: Math.random() * 0xffffff } ) );

        object.position.x = Math.random() * 800 - 400;
        object.position.y = Math.random() * 800 - 400;
        object.position.z = Math.random() * 800 - 400;

        object.rotation.x = Math.random() * 2 * Math.PI;
        object.rotation.y = Math.random() * 2 * Math.PI;
        object.rotation.z = Math.random() * 2 * Math.PI;

        object.scale.x = Math.random() + 0.5;
        object.scale.y = Math.random() + 0.5;
        object.scale.z = Math.random() + 0.5;

        Menu_scene.add( object );

    }


}

function backgroundanimate() {
    requestAnimationFrame( backgroundanimate );
    backgroundrender();

}

function backgroundrender() {
    theta += 0.1;
    Menu_camera.position.x = radius * Math.sin( THREE.Math.degToRad( theta ) );
    Menu_camera.position.y = radius * Math.sin( THREE.Math.degToRad( theta ) );
    Menu_camera.position.z = radius * Math.cos( THREE.Math.degToRad( theta ) );
    Menu_camera.lookAt( Menu_scene.position );
    Menu_camera.updateMatrixWorld();
    Menu_renderer.render( Menu_scene, Menu_camera );

}

function MenuStart(){
    ///初始化菜单背景
    backgroundScene();
    backgroundanimate();

}

///////////////////////////////游戏场景初始化////////////////////////////////////////////////////
var status_game = 1; //闯关状态 0 --失败 ；1 --成功 ；2 -- 成功进入中心区 ；3--停留在本块
var score = 0;//记录分数;
var bufferScore = 1;
var boxList = new Array();//盒子出现的次序

var step = 0;//记录实际块数
var people;//人物模型
var secondstart,secondend,timeSpan;//时间间隔
var len;//实际唯一长度
var element;
var direct = 0;//方块添加的方向 0--x；1--y；
var res = 0;
var x,y,z,x1,z1;
var boxScore = new Array(1,1,1,3,5,1,2,1,1,3,2,1,10,1,1,3,5,2,1,1);
var boxlength = new Array(240,300,400,180,280,140,350,220,240,310,350,200,380,170,180,220,240,350,240,220);
var camera_x,camrea_z,camera_xc,camera_zc;
var stopCamera = 0;
var boxStyle = new Array(
    0.2450125560063181,
    0.4349245175562855,
    0.035676138876020724,
    0.8418592276210253,
    0.646334703720356,
    0.6911277243070633,
    0.855223581680332,
    0.5388044274413362,
    0.8936463199108244,
    0.9241607791887734,
    0.9663549182152664
);//所有的盒子的样式




var stop  =null;
var renderer;
function initThree() {
    if(renderer)
        document.getElementById('canvas-frame').removeChild(renderer.domElement)
    width = document.getElementById('canvas-frame').clientWidth;
    height = document.getElementById('canvas-frame').clientHeight;
    renderer = new THREE.WebGLRenderer({
        antialias : true
    });
    renderer.setSize(width, height);
    document.getElementById('canvas-frame').appendChild(renderer.domElement);
    renderer.setClearColor(0xFFFFFF, 1.0);
    renderer.shadowMapEnabled = true;

}

var camera;
function initCamera() {
    camera = new THREE.PerspectiveCamera(45, width / height, 1, 10000);

    camera.position.x = 500;
    camera.position.y = 700;
    camera.position.z = 600;
    camera.up.x = 0;
    camera.up.y = 1;
    camera.up.z = 0;
    camera.lookAt({
        x : 0,
        y : 0,
        z : 0
    });
}

var scene;
function initScene() {
    scene = new THREE.Scene();

}

var light;
function initLight() {
    var ambientLight = new THREE.AmbientLight(0xFFFFFF);//0X0c0c0c);
    scene.add(ambientLight);

    light = new THREE.DirectionalLight(0XFFF, 1.0, 0);
    light.position.set(200, 400, -100);
    light.castShadow = true;
    scene.add(light);

    light = new THREE.DirectionalLight(0X0c0c0c, 1.0, 0);
    light.position.set(4000, 400, 0);
    scene.add(light);
}

var cube;
var mesh;
function initObject() {
    var planeGeometry = new THREE.PlaneGeometry(40000, 40000);
    var planeMaterial = new THREE.MeshBasicMaterial({ color: 0XD4D8E3 });
    var plane = new THREE.Mesh(planeGeometry, planeMaterial);
    plane.position.set(0, 0, 0);
    plane.rotation.x = -0.5 * Math.PI;
    plane.receiveShadow = true;
    scene.add(plane);
    console.log("平面加载成功");

    //初始化场景
    var geometryStart = new THREE.BoxGeometry( 120, 70, 120 );
    var material = new THREE.MeshLambertMaterial( { color: 0.8418592276210253*0xffffff} );//color: Math.random() * 0xffffff
    var mesh = new THREE.Mesh(geometryStart, material);
    mesh.position.set(0,35,120);
    mesh.castShadow = true;
    mesh.receiveShadow = true;
    scene.add(mesh);
    boxList.push(mesh);
    console.log("物体一加载成功");

    var geometryStart = new THREE.BoxGeometry( 120, 70, 120 );
    var material = new THREE.MeshLambertMaterial( { color: 0.6911277243070633* 0xffffff} );//color: Math.random() * 0xffffff
    var mesh = new THREE.Mesh(geometryStart, material);
    mesh.position.set(0,35,-120);
    mesh.castShadow = true;
    mesh.receiveShadow = true;
    scene.add(mesh);
    boxList.push(mesh);
    console.log("物体二加载成功");

    //初始化人物
    var sphereGeometry = new THREE.SphereGeometry(25, 30, 30);
    var sphereMaterial = new THREE.MeshLambertMaterial({ color: 0.1916077780770673 * 0xffffff});
    people = new THREE.Mesh(sphereGeometry, sphereMaterial);
    people.castShadow = true;
    people.position.set(0,105,120);
    scene.add(people);
    console.log("人物一加载成功");

}

function threeStart() {
    initThree();
    initCamera();
    initScene();
    initLight();
    initObject();
    renderer.render(scene, camera);
    console.log("场景重新渲染");
}


function ainmationPop() {
    var mesh = boxList[step];
    mesh.position.y -= 0.2;
    people.position.y -= 0.2;
    if((new Date().getTime() - secondstart)>=5000 || res  == 1){
        return;
    }
    requestAnimationFrame(ainmationPop);
    renderer.render(scene, camera);

}

//  stop = window.requestAnimationFrame(ainmationJumpX);
function ainmationJumpX(){
    console.log("正在渲染");

    people.position.z -=9;
    people.position.y = 100+Math.sqrt(len*len/4-(people.position.z-(z+z1)/2)*(people.position.z-(z+z1)/2));
    stop = window.requestAnimationFrame(ainmationJumpX);
    renderer.render(scene, camera);

    if(people.position.z < z){
        theOtherPart();
    }
}

function ainmationJumpY(){

    console.log("正在渲染");

    people.position.x -=9;
    people.position.y = 100+Math.sqrt(len*len/4-(people.position.x-(x+x1)/2)*(people.position.x-(x+x1)/2));

    stop = window.requestAnimationFrame(ainmationJumpY);
    renderer.render(scene, camera);

    if(people.position.x < x){
        theOtherPart();
    }

}

function ainmationCameraMoveY(){
    console.log("相机移动位置 x-");
    camera.position.x-=9 ;
    camera.position.z =(camera_z -camera_zc)/(camera_x-camera_xc)*(camera.lookAt.x)+camera_z-(camera_z -camera_zc)/(camera_x-camera_xc)*camera_x;
    camera.position.y = 600;


    renderer.render(scene, camera);

    stopCamera = window.requestAnimationFrame(ainmationCameraMoveY);
    if( (camera.position.x)< camera_xc){

        console.log("相机x坐标--》到达极限");
        theOtherCameraPart();
    }
}

function ainmationCameraMoveX(){
    console.log("相机移动位置 z-");
    camera.position.z-=9;
    camera.position.x =(camera_z -camera_zc)/(camera_x-camera_xc)*(camera.lookAt.x)+camera_z-(camera_z -camera_zc)/(camera_x-camera_xc)*camera_x;

    stopCamera = window.requestAnimationFrame(ainmationCameraMoveX);
    renderer.render(scene, camera);
    if(camera.position.z < camera_zc){
        console.log("相机y坐标--》到达极限");
        theOtherCameraPart();
    }
}

////////////////////////////////////////////////////////游戏逻辑相代码///////////////////////////////////////////////
function startGame(){
    getMaxscore();
    //切换界面
    document.getElementById("canvas-background").style .display = "none";
    document.getElementById("canvas-menu").style.display = "none";
    document.getElementById("canvas_end").style.display = "none";
    document.getElementById("canvas-frame").style.display = "block";

    threeStart();
    element= document.getElementById("canvas-frame");
    element.addEventListener("mousedown", onMouseDown, false);
    element.addEventListener("mouseup", onMouseUp, false);
}



function onMouseDown(){
    res = 0;
    //获取当前时间--记录秒数
    secondstart = new Date().getTime();
    console.log("鼠标按下时间"+secondstart);
    //执行弹射动画,最多执行5s
    ainmationPop();

}

function onMouseUp(){
    res = 1;
    people.position.y = 90;
    boxList[step].position.y = 35;

    renderer.render(scene, camera);

    //获取当前时间--记录秒数
    secondend = new Date().getTime();
    console.log("鼠标弹起时间"+secondend);
    //计算时间间隔 | 计算实际位移长度
    timeSpan = secondend -secondstart;
    console.log("时间间隔为========"+timeSpan);
    len = 0.2 * timeSpan;
    console.log("实际位移长度======="+len);


    console.log("判定前的人物坐标x:"+people.position.x+" y:"+people.position.y+" z:"+people.position.z);
    //判断游戏是否结束
    //1、获取起跳块的中心点坐标以及半径
    var mesh = boxList[step];
    var px1 = mesh.position.x;
    var py1 = mesh.position.y;
    var pz1 = mesh.position.z;
    var r1 = mesh.geometry.parameters.depth/2;

    //2、获取终点块的中心坐标以及半径
    var mesh2 = boxList[step+1];
    var px2 = mesh2.position.x;
    var py2 = mesh2.position.y;
    var pz2 = mesh2.position.z;
    var r2 = mesh2.geometry.parameters.depth/2;

    //3、判断人物的起跳点 -- y轴坐标确定
    var Start_peopel_x,Start_peopel_z;
    //沿z直线位移

    if(px2 == px1){
        Start_peopel_x = px2;
        Start_peopel_z = people.position.z;

        direct = 0;
    }

    //沿x-直线位移
    if(pz2 == pz1){
        Start_peopel_x = people.position.x;
        Start_peopel_z = pz2;

        direct = 1;
    }

    console.log("判定移动的方向是"+direct);
    console.log("判定后的实际坐标x:"+Start_peopel_x+" y:"+people.position.y+" z:"+Start_peopel_z);

    //4、获取位移之后的坐标,顺道判断游戏是否结束
    if(direct == 0){
        console.log("此时沿z轴负方向移动");
        people.position.z =  Start_peopel_z  - len;
        people.position.x =  Start_peopel_x;
        console.log(people.position.z);
        //console.log("===========================");
        console.log((pz1-r1)+" ======"+(pz2+r2)+"========"+(pz2-r2));

        console.log(people.position.z < (pz1-r1) && people.position.z>(pz2+r2));
        console.log(people.position.z<(pz2-r2));
        if(people.position.z < (pz1-r1) && people.position.z>(pz2+r2)  || people.position.z<(pz2-r2)){
            //游戏结束

            status_game = 0;
            console.log("0 _游戏结束");
        }

        else if(people.position.z>(pz1-r1)){
            //停留在本块
            status_game = 3;
            console.log("本块");

        }

        //if(people.position.z<=(pz2+r1) && people.position.z>=(pz2-r1)){
        else{
            status_game = 1;
            console.log("继续");
        }

        x= people.position.x;
        y= people.position.y;
        z= people.position.z;
        z1= people.position.z+len;


        people.position.z += len;

        stop = window.requestAnimationFrame(ainmationJumpX);

    }
    else{
        console.log("此时沿x轴负方向移动");
        people.position.x =  Start_peopel_x -len;
        people.position.z =  Start_peopel_z;
        console.log("计算出人物实际的跳动目标x:"+people.position.x+" y:"+people.position.y +" z:"+people.position.z );
        console.log((px2-r2)+"======================="+(px2+r1)+"====================="+(px1-r1));
        if(people.position.x<(px1-r1) && people.position.x>(px2+r1) || people.position.x<(px2-r2)){
            status_game = 0;
            console.log("1_游戏结束");
        }
        else if(people.position.x>(px1-r1)){
            //停留在本块
            status_game = 3;
            console.log("1_本块");
        }

        //if(people.position.x>=(px2+r1) && people.position.x>=(px2-r1)){
        else{
            status_game = 1;
            console.log("1_继续");
        }

        x= people.position.x;
        y= people.position.y;
        z= people.position.z;
        x1= people.position.x+len;


        people.position.x += len;

        stop = window.requestAnimationFrame(ainmationJumpY);

    }

}


function endGame(){
    getMaxscore();



    //跟新数据
    if(score > MaxScore){
        MaxScore = score;
        $.ajax({
            type: "POST",
            url: "/score/updateScore.do",
            data: {"ID":document.getElementById("Maxscore").value,"score":MaxScore},
            async: false,
            success: function(date) {
                console.log(date);
                if(date.status == 0)
                   console.log("修改成绩为"+MaxScore);
                else
                    alert(date.msg);


            },
            error: function(date) {
                alert("服务器繁忙!");
            }
        });

    }


    document.getElementById("canvas-background").style .display = "none";
    document.getElementById("canvas-menu").style.display = "none";
    document.getElementById("canvas_end").style.display = "block";
    document.getElementById("canvas-frame").style.display = "none";
    document.getElementById("height_score").innerHTML = "历史最高分"+MaxScore;
    document.getElementById("score_laber").innerHTML = score.toString();
    document.getElementById("score").innerHTML = "0";
    //重置游戏

    boxList = new Array();
    direct = 0;
    res = 0;
    score = 0;
    step = 0;
    bufferScore = 1;
}



function theOtherPart(){
    console.log("调用这个");
    if (stop)
        window.cancelAnimationFrame(stop);
    //window.cancelAnimationFrame.stop;
    stop = 0;
    people.position.z = z;
    people.position.x = x;
    if(status_game  == 0) {
        people.position.y = 25;
    }

    else{
        people.position.y = 95;
    }
    renderer.render(scene, camera);
    //	var status_game = 1; //闯关状态 0 --失败 ；1 --成功 ；2 -- 成功进入中心区 ；3--停留在本块

    if(status_game == 1) {



        //随机获取新块
        var i = Math.floor(Math.random() * 10);
        //var box =boxStyle[i];
        var geometry = new THREE.BoxGeometry(120, 70, 120);

        var material = new THREE.MeshLambertMaterial({color: boxStyle[i]*0xffffff});
        var mesh = new THREE.Mesh(geometry, material);
        mesh.castShadow = true;
        mesh.receiveShadow = true;
        //结算
        bufferScore = boxScore[i];
        score += bufferScore;

        document.getElementById("score").innerHTML = score;

        //随机生成方向 0-1
        direct = Math.round(Math.random());

        //随机获取距离
        var dest = boxlength[i];


        if (direct == 0) {
            mesh.position.x = boxList[step + 1].position.x;
            mesh.position.y = 35;
            mesh.position.z = boxList[step + 1].position.z - dest;
            boxList.push(mesh);
            scene.add(mesh);


        }

        if (direct == 1) {
            mesh.position.x = boxList[step + 1].position.x - dest;
            mesh.position.y = 35;
            mesh.position.z = boxList[step + 1].position.z;

            boxList.push(mesh);
            scene.add(mesh);

        }

        renderer.render(scene, camera);

        //步数++
        step++;

        //移动相机


        //相机即将移动的位置
        camera_xc = (boxList[step].position.x + boxList[step + 1].position.x) / 2 + 500;
        camera_zc = (boxList[step].position.z + boxList[step + 1].position.z) / 2 + 700;
        //当前相机的位置
        camera_x = camera.position.x;
        camera_z = camera.position.z;

        camera.position.x = (boxList[step].position.x + boxList[step + 1].position.x) / 2 + 500;
        camera.position.z = (boxList[step].position.z + boxList[step + 1].position.z) / 2 + 700;
        renderer.render(scene, camera);
        //  stopCamera = window.requestAnimationFrame(ainmationCameraMoveY);

    }

    if(status_game == 3){
        //null-->直接进入下一次

    }

    if(status_game  == 0){
        //游戏结束
        setTimeout("endGame()",350);
        element.removeEventListener("mousedown", onMouseDown, false);
        element.removeEventListener("mouseup", onMouseUp, false);
        var count = scene.children.length;
        while (count--) {
            if (scene.children[count])
                scene.remove(scene.children[count]);
        }


    }







}

function toHome(){
    window.location.href = "../index.jsp";
}




//            function theOtherCameraPart(){
//                console.log("调用这个");
//                if (stop)
//                    window.cancelAnimationFrame(stop);
//                //window.cancelAnimationFrame.stop;
//                stop = 0;
//						camera.position.x = (boxList[step].position.x + boxList[step + 1].position.x) / 2 + 500;
//	                   camera.position.z = (boxList[step].position.z + boxList[step + 1].position.z) / 2 + 700;
//	                    renderer.render(scene, camera);
//			}
var MaxScore;

function getMaxscore(){
    console.log("执行最高分查询");
    var id =document.getElementById("Maxscore").value;

    $.ajax({
        type: "POST",
        url: "score/searchByID.do",
        data: {"ID":id},
        async: false,
        success: function(res) {
            MaxScore = res.data.score;
            console.log("最高分"+MaxScore);
        },
        error: function(date) {
            alert("服务器繁忙!");
        }
    });


}